package com.ms.p2p.controller.admin;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ms.common.utils.MsDateUtils;
import com.ms.p2p.controller.BaseController;
import com.ms.p2p.entity.loan.LoanCategory;
import com.ms.p2p.entity.system.AdminUser;
import com.ms.p2p.provider.LoanCategoryProvider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * @Description: 项目类型（后台）
 */

@Controller
@RequestMapping({"/admin/borrowType"})
public class AdminLoanTypeController extends AdminBaseController {

	@Reference
	private LoanCategoryProvider typeService;
	
	/**
	 * 所有项目类型
	 * @return
	 */
	@RequestMapping({"/typeList"})
	public String typeList(HttpServletRequest request,HttpSession session){
		List<LoanCategory> types = typeService.findAll();
		request.setAttribute("types", types);
		return "manage/borrow/type/typeList";
	}
	
	/**
	 * 到添加修改页面
	 * @return
	 */
	@RequestMapping({"/toAddAndModifyType"})
	public String toAddAndModifyType(String typeId, Model model){

		if(StringUtils.isNotBlank(typeId)){
			LoanCategory type = typeService.findById(typeId);
			model.addAttribute("type", type);
		}
		return "manage/borrow/type/addAndModifyType";
	}
	
	/**
	 * 添加和修改
	 * @param request
	 * @param session
	 * @param type
	 * @return
	 */
	@RequestMapping(value={"/addAndModifyType"},produces = { "application/json;charset=UTF-8" })
	@ResponseBody
	public String addAndModifyType(HttpServletRequest request,HttpSession session,LoanCategory type) throws IllegalAccessException, InvocationTargetException, IntrospectionException{
		AdminUser emp = getCurrentEmp();
		String typeId = request.getParameter("typeId");
		int result = 0;
		if (emp != null) {
			if(typeId != null && !("".equals(typeId))){
				type.setId(Integer.parseInt(typeId));
				type.setUptime(MsDateUtils.getTime());
				result = typeService.update(type);
			} else {
				type.setAddtime(MsDateUtils.getTime());
				result = typeService.insert(type);
			}
		}
		if(result>0){
			return "操作成功";
		} else {
			return "操作失败";
		}
	}

	@Override
	public boolean getBinderFlag() {
		return true;
	}
}
